<?php

namespace app\admin\controller\service\skill;

use app\common\controller\Backend;
use think\Db;
use think\Exception;

/**
 * 服务人员信息管理
 *
 * @icon fa fa-circle-o
 */
class Skill extends Backend
{

    /**
     * Skill模型对象
     * @var \app\admin\model\service\skill\Skill
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\service\skill\Skill;
        $this->view->assign("sexList", $this->model->getSexList());
        $this->view->assign("eduList", $this->model->getEduList());
        $this->view->assign("experList", $this->model->getExperList());
        $this->view->assign("isRestList", $this->model->getIsRestList());
        $this->view->assign("isTrainList", $this->model->getIsTrainList());
        $this->view->assign("stateList", $this->model->getStateList());
    }



    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        foreach ($list as &$val)
        {
            $val->shop_name = $val->shop_id?\app\admin\model\service\shop\Shop::where(['id'=>$val->shop_id])->value('abbr'):'';
            $val->category_name = \app\admin\model\service\Category::where(['id'=>$val->category_id])->value('name');
            $val->skill_cate_name = \app\admin\model\service\skill\Skillcate::where(['id'=>$val->skill_cate_id])->value('name');
            $val->goodsname = $val->goods_ids?model('app\admin\model\service\Goods')->getGoodsList($val->goods_ids):'';
            $val->skillmoney = \app\admin\model\service\User::where('user_id',$val->user_id)->field('money,shop_money')->find();
            $val->already_accept_nums = \app\admin\model\service\order\Order::where(['skill_id'=>$val->id,'status'=>['>',1],'starttime'=>['>',strtotime(date("Y-m-d",time()))]])->count();
            $val->update_time = $val->updatetime?date("Y-m-d",$val->updatetime):'';
            $val->create_time = date("Y-m-d",$val->createtime);
        }
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        if($params['city'])
        {
            $address = explode('/',$params['city']);
            $params['province'] = $address[0];
            $params['city'] = $address[1];
            $params['district'] = $address[2]??'';
        }
        $result = false;
        $user = \app\admin\model\service\User::get(['user_id'=>$params['user_id']]);
        $user['is_skill'] == 1 && $this->error('当前用户已申请成为服务者');
        $count = $this->model->where('state',1)->count();
        $params['code'] = str_pad(date('d').$count,8,0);
        $params['state'] = 1;
        $params['updatetime'] = time();
        $params['accept_nums'] = \app\api\model\service\ProjectConfig::getProjectConfig('accept_nums');
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            model('app\admin\model\service\User')->where('user_id',$params['user_id'])->update(['is_skill'=>1]);
            $skill = db('service_skill')->where('user_id',$user['user_id'])->find();
            \app\admin\model\service\skill\Applyskill::createTime($skill['id']);
            unset($skill['id']);
            $skill['applytype'] = 1;
            $perfect = new \app\admin\model\service\skill\Perfect($skill);
            $perfect->allowField(true)->save();
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $row->city = $row->province.'/'.$row->city.'/'.$row->district;
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        if($params['city'])
        {
            $address = explode('/',$params['city']);
            $params['province'] = $address[0];
            $params['city'] = $address[1];
            $params['district'] = $address[2] ?? '';
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    public function deduct($ids = null)
    {
        $row = $this->model->get($ids);
        if($this->request->isPost())
        {
            $params = $this->request->post('row/a');
            Db::startTrans();
            try{
                $params['skill_ensure']>$row->ensure_price && $this->error('保证金不足,无法扣除');
                \app\api\model\service\Skill::money(-$params['skill_ensure'], $row->user_id, $params['skill_note']);
                Db::commit();
                $this->success('保证金已扣除');
            } catch (Exception $e) {
                Db::rollback();
                $this->error('保证金扣除失败',$e->getMessage());
            }
        }
        $this->assign(['row'=>$row]);
        return $this->view->fetch();
    }
    

}
